// src/directives/permission.ts
import type { Directive, App } from 'vue'
import { useAuthStore } from '@/stores/auth'

// 权限指令配置类型
type PermissionOptions = {
  action?: 'remove' | 'disable' // 处理方式：移除元素或禁用按钮
  logic?: 'some' | 'every'      // 校验逻辑：满足任意/所有权限
}

// 权限校验核心方法
const checkPermission = (value: string | string[], permissions: string[], options: PermissionOptions) => {
  const actions = Array.isArray(value) ? value : [value]
  
  const hasPermission = options.logic === 'every' 
    ? actions.every(action => permissions.includes(action))
    : actions.some(action => permissions.includes(action))

  return hasPermission
}

const permissionDirective: Directive<HTMLElement, string | string[] | { action: string, value: string|string[] }> = {
  mounted(el, binding) {
    const authStore = useAuthStore()
    const permissions = authStore.permissions
    
    // 解析指令参数
    const options: PermissionOptions = {
      action: 'remove',
      logic: 'some',
      ...(typeof binding.value === 'object' && !Array.isArray(binding.value) 
        ? binding.value 
        : { value: binding.value })
    }

    const permissionValue = typeof binding.value === 'object' && !Array.isArray(binding.value)
      ? binding.value.value
      : binding.value

    const hasPermission = checkPermission(permissionValue, permissions, options)

    if (!hasPermission) {
      if (options.action === 'remove') {
        el.parentNode?.removeChild(el)
      } else {
        el.classList.add('is-disabled')
        if (el.tagName === 'BUTTON') {
          el.disabled = true
        } else if (el.__vue__?.props) { // 处理Element Plus组件
          el.__vue__.props.disabled = true
        }
      }
    }
  }
}

// 注册指令
export function setupPermissionDirective(app: App) {
  app.directive('permission', permissionDirective)
}